<template>
  <el-dialog
    :close-on-click-modal="false"
    width="95%"
    class="material-select-dialog"
    :model-value="modelValue"
    @update:model-value="handleVisibleChange"
  >
    <div class="dialog-content">
      <el-container class="material-container">
        <el-main class="material-main">
          <index
            v-if="modelValue"
            @selection-change="handleMaterialSelect"
            :showSelection="true"
          ></index>
        </el-main>
      </el-container>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import index from '@/views/material/course/index.vue'
import { ref, watch } from 'vue'
import { useCentreStore } from '@/store/modules/lession/centre'

const selectedMaterials = ref<any[]>([])
const emit = defineEmits(['update:modelValue', 'confirm', 'cancel'])
const centreStore = useCentreStore()

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
})

const handleMaterialSelect = (selection: any[]) => {
  selectedMaterials.value = selection
  centreStore.setSelectedMaterials(selectedMaterials.value)
}

const handleConfirm = () => {
  emit('confirm', selectedMaterials.value)
  emit('update:modelValue', false)
}

const handleCancel = () => {
  emit('cancel')
  emit('update:modelValue', false)
}

const handleVisibleChange = (val: boolean) => {
  emit('update:modelValue', val)
}

watch(
  () => props.modelValue,
  (newVal) => {
    if (!newVal) {
      selectedMaterials.value = []
    }
  }
)
</script>

<style lang="scss" scoped>
.material-select-dialog {
  :deep(.el-dialog) {
    margin-top: 5vh !important;
    min-width: 1200px;

    .el-dialog__body {
      max-height: 80vh;
      overflow-y: auto;
      padding: 10px 20px;
    }
  }
}

.dialog-content {
  min-height: 300px;
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
